package web_commands

import db.User
import org.hibernate.{ Session, SessionFactory }
import org.hibernate.cfg.Configuration
import db.UserManager

/**
 * Created by IntelliJ IDEA.
 * User: Tamar
 * Date: 4/13/11
 * Time: 10:48 PM
 * To change this template use File | Settings | File Templates.
 */

class NewUser(firstName: String, lastName: String, email: String,
  password: String, birthday: String) {

  /**
   * The method checks if a user with the given email already exits in the database.<br>
   * If it doesn't exists creates a new user in the database and returns true,
   * otherwise returns false.
   */
  def execute(): User = {
    val cfg = new Configuration()
    var sessionFactory = null.asInstanceOf[SessionFactory]
    var session = null.asInstanceOf[Session]
    try{
    sessionFactory = cfg.configure().buildSessionFactory()
    session = sessionFactory.openSession()
    val query = session.createQuery("from Users where email='" + email + "'")
    val list = query.list()
    if (list.isEmpty()) {
      val user = new User()
      user.setFirstName(firstName)
      user.setLastName(lastName)
      user.setEmail(email)
      user.setPassword(password)
      user.setBirthday(birthday)

      val userManager = new UserManager(session)
      userManager.saveUser(user)
      session.flush()
      return user
    }
    session.flush()
    }catch { case (e : Exception)=>e.printStackTrace }
    return null
  }
}
